import { service } from './service'
import { AxiosResponse } from 'axios'
interface ApiError extends Error {
  response: AxiosResponse;
  config: AxiosResponse & { url: string };
}

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function $get (url: string, params = {}, config?: any) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params,
        paramsSerializer: function (params: any) {
          return new URLSearchParams(params).toString()
        },
        signal: config?.signal
      })
      .then((response: AxiosResponse) => {
        resolve(response)
      })
      .catch((err: ApiError) => {
        reject(err)
      })
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function $post (url: string, data = {}) {
  return new Promise((resolve, reject) => {
    service.post(url, {
      ...data
      // signal: config?.signal
    }).then(
      (response: AxiosResponse) => {
        resolve(response)
      },
      (err: ApiError) => {
        reject(err)
      }
    )
  })
}
